﻿namespace DistrRTgen
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.IO;
    using System.Reflection;
    using System.Xml.Serialization;

    [XmlRoot("WorkUnitList")]
    public class WorkUnitList : MarshalByRefObject
    {
        private DistrRTgenConnector _Connection;
        //private int _MinAvailableWU = 8;
        private List<WorkUnit> _WorkUnits;
        [XmlIgnore]
        public bool SaveEnabled;

        public WorkUnitList()
        {
            Logger.AddLogLine("Initializing WorkUnitList()", LoggerLevel.LOG_DEBUG);
            this._WorkUnits = new List<WorkUnit>();
            this._Connection = new DistrRTgenConnector();
        }

        public void Add(WorkUnit WU)
        {
            this._WorkUnits.Add(WU);
            this.Save();
        }

        public IEnumerator GetEnumerator()
        {
            return this._WorkUnits.GetEnumerator();
        }

        public WorkUnit GetFirstAvailable(int MinAvailableWU)
        {
            int NumAvailable = 0;
            for (int i = 0; i < this._WorkUnits.Count; i++)
            {
                if (!this[i].InUse)
                {
                    NumAvailable++;
                }
            }
            if (NumAvailable < MinAvailableWU)
            {
                WorkUnit[] WUList = this._Connection.RequestWork(MinAvailableWU - NumAvailable);
                if (WUList != null)
                {
                    for (int i = 0; i < WUList.Length; i++)
                    {
                        this.Add(WUList[i]);
                    }
                }
            }
            for (int i = 0; i < this._WorkUnits.Count; i++)
            {
                if (!this[i].InUse)
                {
                    return this[i];
                }
            }
            return null;
        }

        public WorkUnit GetWUByPartID(uint PartID)
        {
            for (int i = 0; i < this._WorkUnits.Count; i++)
            {
                if (this._WorkUnits[i].PartID == PartID)
                {
                    return this._WorkUnits[i];
                }
            }
            return null;
        }

        public static WorkUnitList LoadWUList()
        {
            try
            {
                Logger.AddLogLine("Loading WUList", LoggerLevel.LOG_DEBUG);
                if (!File.Exists("WUList.xml"))
                {
                    return new WorkUnitList();
                }
                FileStream fs = File.OpenRead("WUList.xml");
                XmlSerializer xs = new XmlSerializer(typeof(WorkUnitList));
                WorkUnitList WUList = (WorkUnitList) xs.Deserialize(fs);
                fs.Close();
                WUList.SaveEnabled = true;
                return WUList;
            }
            catch (Exception ex)
            {
                Logger.AddLogLine(string.Concat(new object[] { "WorkUnitList::Load() :", ex.GetType(), " ", ex.Message }), LoggerLevel.LOG_ALERT);
            }
            return new WorkUnitList();
        }

        public void Remove(WorkUnit WU)
        {
            WU.TriggerRemoved();
            this._WorkUnits.Remove(WU);
            this.Save();
        }

        public void Remove(uint PartID)
        {
            for (int i = 0; i < this._WorkUnits.Count; i++)
            {
                if (this[i].PartID == PartID)
                {
                    this.Remove(this[i]);
                }
            }
        }

        public void Save()
        {
            if (this.SaveEnabled)
            {
                Logger.AddLogLine("Serializing WUList", LoggerLevel.LOG_DEBUG);
                try
                {
                    FileStream fs = new FileStream("WUList.xml", FileMode.Create);
                    try
                    {
                        new XmlSerializer(base.GetType()).Serialize((Stream) fs, this);
                    }
                    catch (Exception ex)
                    {
                        Logger.AddLogLine("Unable to serialize WorkUnit list into XML:" + ex.Message, LoggerLevel.LOG_ERROR);
                    }
                    fs.Close();
                }
                catch (Exception ex)
                {
                    Logger.AddLogLine("Unable to open WUList.xml: " + ex.Message + ". Can't save parts", LoggerLevel.LOG_ALERT);
                }
            }
        }

        public int Count
        {
            get
            {
                return this._WorkUnits.Count;
            }
        }

        public WorkUnit this[int i]
        {
            get
            {
                return this._WorkUnits[i];
            }
        }

        public List<WorkUnit> WorkUnits
        {
            get
            {
                return this._WorkUnits;
            }
        }
    }
}

